package com.atomy.bigeventsservice.filter;
import com.alibaba.fastjson.JSONObject;
import com.atomy.bigeventsservice.entity.Result;
import com.atomy.bigeventsservice.utils.JwtUtils;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import jakarta.servlet.*;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("---初始化过滤器-----");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        String url=request.getRequestURI().toString();
        log.info("----请求路径----"+url);
        //        2. 如果请求是login  register放行
        if ((url.contains("/login")||url.contains("/register"))){
            filterChain.doFilter(request,response);
            return;
        }

//        3. 如果不是但是带cookies 放行 ：检验交给过滤器
//        如果请求不是login且不包含cookies 不放行
        if ((!(url.contains("/login")||url.contains("/register"))) && !StringUtils.hasLength(request.getHeader("token"))){
            Result responseResult= Result.error("未登录, 没有token");
            log.info("未登录, 没有token");
            String json= JSONObject.toJSONString(responseResult);
            response.setContentType("application/json;charest=utf-8");
            response.getWriter().write(json);
            return;
        }
//        4. 解析token是否正常存在
        String token=request.getHeader("token");
        try {
            JwtUtils.parseJWT(token);
            log.info("令牌合法, 放行");
        }catch (Exception e){
            log.info("令牌不合法, 不放行");
//            e.printStackTrace();
            Result responseResult=Result.error("令牌不合法");
            String json= JSONObject.toJSONString(responseResult);
            response.setContentType("application/json;charest=utf-8");
            response.getWriter().write(json);
            return;
        }
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
